package com.zimmur.app.mocolink.background.aop;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.zimmur.app.mocolink.background.common.ReturnJsonEntity;
import com.zimmur.app.mocolink.background.common.StatusCodeEnum;
import com.zimmur.app.mocolink.background.util.SecretUtil;
import com.zimmur.app.mocolink.domain.model.AppUser;
import com.zimmur.app.mocolink.service.IAppUserService;

public class UserCheckInterceptor extends HandlerInterceptorAdapter {
	private Logger log = LoggerFactory.getLogger(UserCheckInterceptor.class);
	@Resource
	private IAppUserService appUserService;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8"); 		
		ReturnJsonEntity entity = new ReturnJsonEntity(StatusCodeEnum.CODE100200);
		String token = request.getHeader("token");
		if(StringUtils.isEmpty(token)){
			response.getWriter().write(JSON.toJSONString(entity));
			return false;
		}
		try {
			entity = new ReturnJsonEntity(StatusCodeEnum.CODE100201);
			//验证是否过期
			/*if(SecretUtil.isTokenExpaire(token)){
				 response.getWriter().write(JSON.toJSONString(entity));
				 return false;
			}*/
			Integer userId = SecretUtil.Instance().getUserId(token);
	        AppUser user=appUserService.selectById(userId);
			if(user == null || !token.equals(user.getAuthToken())){
				response.getWriter().write(JSON.toJSONString(entity));
				return false;
			}
			
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			entity = new ReturnJsonEntity(StatusCodeEnum.CODE100000);
			response.getWriter().write(JSON.toJSONString(entity));
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) throws Exception {
	}
}
